%生成正弦函数波形
% hdlsim("Modelsim");
    fs = 48000;  % 采样率：1 GHz
    freqs  = [1000 ];  % 混合频率
    amps   = [0.001];
    % ==== 时间轴 ====
    t = 0 : 1/fs : 1;
    % ==== 合成信号 ====
    sin_wave = zeros(size(t));
    for i = 1:length(freqs)
        sin_wave = sin_wave + amps(i) * cos(2 * pi * freqs(i) * t );
    end

% 定义窗口长度
    windowLength = 65;
% 定义过采样率
    osr_order = 4 ;

% 不同Beta下的Kaiser窗定义
    betas = [0.5, 2, 6];
    for i = 1:length(betas)
        windows{i} = kaiser(windowLength, betas(i));
    end
    fir_param_0 = fir1(windowLength,20000/(4800*64),"low",kaiser(windowLength+1,0),"noscale");
    fir_param_1 = fir1(windowLength,20000/(4800*64),"low",kaiser(windowLength+1,2),"noscale");
    fir_param_2 = fir1(windowLength,20000/(4800*64),"low",kaiser(windowLength+1,6),"noscale");

%归一化
    fir_param_0 = fir_param_0 / max(fir_param_0);
    fir_param_1 = fir_param_1 / max(fir_param_1);
    fir_param_2 = fir_param_2 / max(fir_param_2);

%选择使用的FIR滤波器
    fir_used = fir_param_1;

% 插值
    interp_data = zeros(1, length(sin_wave)*osr_order + 1);  % 插值后总长度
    for i=0 : (length(sin_wave)-1)
        interp_data(1+i*osr_order) = sin_wave(i+1);
    end

% 数据经过滤波器
    phaset = (windowLength-1)/osr_order;
    if(phaset < 0)
        err("错误的窗口长度或过采样率!");
    end

    for i=1 : length(sin_wave)

        % j 处理2π/osr_order 相位的数据
        for j=1 : osr_order-1

            % 定义X(n)
            phase_samp_src = zeros(1,(windowLength-1)/osr_order);
            data_temp = 0;
            % 处理滤波器X(n)
            for k=0: length(phase_samp_src)-1
                temp = i-k+length(phase_samp_src);
                if (temp) <= 0
                    phase_samp_src(k+1) = sin_wave(i-k);
                end
                data_temp = fir_used((j-1)*phaset+k+1) * phase_samp_src(k+1) + data_temp;
            end
            data_temp = data_temp / phaset;
            interp_data((i-1)*osr_order + j) = data_temp;
        end
    end


% 绘制图像
figure;
hold on;
colors = lines(length(windows));
for i = 1:length(windows)
    plot(windows{i}, 'Color', colors(i,:), ...
            'DisplayName', sprintf('Beta=%.f', betas(i)));
end
title('Different Beta Values of Kaiser Window');
xlabel('Sample Index'); ylabel('Amplitude');
legend show;
grid minor;
hold off;

figure();
hold on;
    plot(fir_param_0,'r');
    plot(fir_param_1,'g');
    plot(fir_param_2,'b');
    title('FIR PARAM');
    legend('FIR_β0', 'FIR_β2', 'FIR_β6');
hold off;